package com.ocom.amqp.core;

import com.ocom.amqp.builder.AbstractAssemblyBuilder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class AmqpBasicBeanProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext context;

    private Map<Class, AbstractAssemblyBuilder> builderMap;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof BasicExpandAssembly) {
            //调用构建
            this.builderMap.get(bean.getClass()).build(bean);
        }
        return bean;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
        //查找所有的封装组件创建器，注入到Map中
        Map<String, AbstractAssemblyBuilder> beansOfType = this.context.getBeansOfType(AbstractAssemblyBuilder.class);
        this.builderMap = new HashMap<>(beansOfType.size());
        Collection<AbstractAssemblyBuilder> values = beansOfType.values();
        values.forEach(builder -> {
            ParameterizedType genericSuperclass = (ParameterizedType) builder.getClass().getGenericSuperclass();
            Class targetClass = (Class)genericSuperclass.getActualTypeArguments()[0];
            this.builderMap.put(targetClass, builder);
        });
    }
}
